package cn.tedu._05weibo.interceptors;

import cn.tedu._05weibo.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
            核心:校验用户的登录状态
                1.登录状态:返回true放行
                2.未登录状态:重定向到login.html,返回false

                提示:
                    1.获取session会话的方法 - request.getSession()
                    2.重定向方法:response.sendRedirect("/login.html")
         */
        log.debug("拦截器使用了~");
        UserVO userVO = (UserVO) request.getSession().getAttribute("user");
        if (userVO!=null){
            return true;
        }
        response.sendRedirect("/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
